package pacote;

import java.io.IOException;
import java.io.StringReader;
import java.rmi.RemoteException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.rpc.ServiceException;
import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import NET.webserviceX.www.GlobalWeather;
import NET.webserviceX.www.GlobalWeatherLocator;
import NET.webserviceX.www.GlobalWeatherSoap;

public class Temperatura {

	/**
	 * @param args
	 * @throws ServiceException 
	 */
	public static void main(String[] args) throws ServiceException {
		Temperatura temp = new Temperatura();
		temp.buscarTemperatura("natal");
	}

	private Element elem;
	
	public int buscarTemperatura(String cidade){
		String temp;
		int temperatura = 0;
		GlobalWeather gb = new GlobalWeatherLocator();
		GlobalWeatherSoap ws;
		try {
			ws = gb.getGlobalWeatherSoap();
			
			temp = ws.getWeather(cidade, "brazil");
			parseStringToXml(temp);
			temperatura = getTemperatura();
			
			
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XPathExpressionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return temperatura;
	}
	
	public void parseStringToXml(String wsdlString) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException{
		
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
	    domFactory.setNamespaceAware(true);
	    DocumentBuilder docBuilder = domFactory.newDocumentBuilder();
	    InputSource is = new InputSource( new StringReader(wsdlString));
	    Document doc = docBuilder.parse(is);
	    this.elem = doc.getDocumentElement();
	}
	
	public int getTemperatura(){
		String temp;
		int temperatura = 0;
		NodeList nl = this.elem.getElementsByTagName( "Temperature" );
		
		for (int i=0; i<nl.getLength();i++){
			NodeList n = nl.item(i).getChildNodes();				
			temp = n.item(0).getNodeValue().trim();
			temp = temp.substring(temp.indexOf("(")+1, temp.indexOf(")")-2);
			temperatura = Integer.parseInt(temp);
		} 
		System.out.println(temperatura);
		return temperatura;
	}
	

}
